package top.zy.admin.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.zy.admin.dao.AdminMapper;
import top.zy.admin.dto.AdminInfo;
import top.zy.admin.entity.Admin;
import top.zy.admin.entity.Permission;
import top.zy.admin.entity.Role;
import top.zy.admin.vo.AdminInfoVo;
import top.zy.admin.vo.AdminPermissionInfo;
import top.zy.common.zymallcommon.utils.exception.ExceptionEnum;
import top.zy.common.zymallcommon.utils.exception.ZymalException;
import top.zy.common.zymallcommon.utils.resp.ApiResponseStatus;
import top.zy.common.zymallcommon.utils.resp.ResponseUtil;
import top.zy.common.zymallcommon.utils.util.IpUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 16:34 2019/7/18
 */
@Service
public class AdminAuthServiceImpl implements AdminAuthService{
    @Autowired
    private AdminMapper adminMapper;


    @Transactional
    @Override
    public AdminInfoVo login(HttpServletRequest request) {
        Subject currentUserSubject=SecurityUtils.getSubject();
        Admin adminUser = (Admin) currentUserSubject.getPrincipal();
        adminUser.setLastLoginIp(IpUtil.getIpAddr(request));
        adminUser.setLastLoginTime(new Date());
        int result=adminMapper.updateByPrimaryKeySelective(adminUser);
        if (result==0){
           throw new ZymalException(ExceptionEnum.UPDATE_FAIL);
        }
        AdminInfoVo adminInfoVo=new AdminInfoVo();
        AdminInfo adminInfo=new AdminInfo();
        adminInfo.setAvatar(adminUser.getAvatar());
        adminInfo.setNickName(adminUser.getNickName());
        adminInfoVo.setToken(String.valueOf(currentUserSubject.getSession().getId()));
        adminInfoVo.setAdminInfo(adminInfo);
        return adminInfoVo;
    }

    @Override
    public AdminPermissionInfo getAdminPermissionInfo() {
        AdminPermissionInfo  adminPermissionInfo=new AdminPermissionInfo();
         Subject subject=SecurityUtils.getSubject();
         Admin adminCurrent= (Admin) subject.getPrincipal();
         Set<String> roles=new TreeSet<>();
        Set<String> perms=new TreeSet<>();
         for (Role role : adminCurrent.getRoles()) {
              roles.add(role.getName());
             for (Permission permission : role.getPermissions()) {
                 perms.add(permission.getPermission());
             }
         }
         adminPermissionInfo.setName(adminCurrent.getUsername());
         adminPermissionInfo.setAvatar(adminCurrent.getAvatar());
         adminPermissionInfo.setRoles(roles);
         adminPermissionInfo.setPerms(perms);
        return adminPermissionInfo;
    }
}
